﻿package lib 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	
	/**
	 * ...
	 * @author kabuto.boy
	 */
	public class Scrubber extends _CustomButton
	{
		private var _scrubbar:Scrubbar;
		private var _filledbar:Sprite;
		
		private var eScrub:Event = new Event("scrub");
		private var eScrubbing:Event = new Event("scrubbing");
		private var eScrubed:Event = new Event("scrubed");
		
		private var sWidth:Number;
		private var left:Number;
		private var right:Number;
		
		public var position:Number;
		
		private var dragging:Boolean = false;
		
		public function Scrubber() 
		{
			_scrubbar = (this.parent as Object).scrubbar;
			_filledbar = (this.parent as Object).filledbar;
			
			sWidth = _scrubbar.width;
			left = _scrubbar.x;
			right = left + sWidth;
			
			this.addEventListener(MouseEvent.MOUSE_DOWN, onEvent);
			this.stage.addEventListener(MouseEvent.MOUSE_UP, onEvent);
		}
		
		private function onEvent(event:*):void
		{
			switch(event.type) {
				case "mouseDown" :
					dragging = true;
					
					var _mouseX:int = this.parent.mouseX;
					
					try {
						_scrubTo(_mouseX);
					} catch (error:*) {
						_scrubbar = (this.parent as Object).scrubbar;
						_filledbar = (this.parent as Object).filledbar;
						_scrubTo(_mouseX);
					}
					
					this.stage.addEventListener(MouseEvent.MOUSE_MOVE, onEvent);
					this.dispatchEvent(eScrub);
					break;
				case "mouseMove" :
					var _x:int = this.parent.mouseX;
					
					if (_x < left)
						_x = left;
					else if (_x > right)
						_x = right
					
					_scrubTo(_x);
					
					position = (this.x - left) / sWidth;
					
					this.dispatchEvent(eScrubbing);
					
					event.updateAfterEvent();
					break;
				case "mouseUp" :
					//this.stopDrag();
					if (dragging) {
						dragging = false;
						this.stage.removeEventListener(MouseEvent.MOUSE_MOVE, onEvent);
						this.dispatchEvent(eScrubed);
					}
					break;
			}
		}
		
		private function _scrubTo(value:Number):void
		{
			this.x = value;
			_filledbar.width = value - left;
		}
		
		public function scrubTo(value:Number):void
		{
			this.x = value * sWidth + left;
			_filledbar.width = this.x - left;
		}
		
	}

}